//
//  GameViewController.m
//  MathKids
//
//  Created by Nguyen Huu Hien on 5/2/14.
//  Copyright (c) 2014 Nguyen Huu Hien. All rights reserved.
//

#import "GameViewController.h"

#define SCORE 1
#define TIME 2

@interface GameViewController ()

@end

@implementation GameViewController
@synthesize imgTimer, imgScore, imgLevel;
@synthesize timer;
@synthesize lbResult, anw_1, anw_2, anw_3, anw_4, mathOperator, audioPlayer, btn_sound;
@synthesize arrScore;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    dictionary_mode = [[NSMutableDictionary alloc]initWithCapacity:5];
    if(!mathOperator.unLimitTime)
    {
        timeCountdown = 45;
        [self startCountDown];
    }
    else
    {
        int type = TIME;
        NSString *value =[NSString stringWithFormat:@"no"];
        [self calculate:value withType:type];
    }
    if(mathOperator.add_minus)
    {
        [dictionary_mode setObject:[NSNumber numberWithInt:1] forKey:@"mod_1"];
    }
    if(mathOperator.multiply_divied)
    {
        [dictionary_mode setObject:[NSNumber numberWithInt:2] forKey:@"mod_2"];
    }
    if(mathOperator.greatest_smallest)
    {
        [dictionary_mode setObject:[NSNumber numberWithInt:3] forKey:@"mod_3"];
    }
    if(mathOperator.mixedOperation)
    {
        [dictionary_mode setObject:[NSNumber numberWithInt:4] forKey:@"mod_4"];
    }
    if(mathOperator.fractions)
    {
        [dictionary_mode setObject:[NSNumber numberWithInt:5] forKey:@"mod_5"];
    }
    dictionary_sound_right = @{
                                @"0" : @"amazing1",
                                @"1" : @"awsome1",
                                @"2" : @"beattentive2",
                                @"3" : @"brilliant1",
                                @"4" : @"congratulations1",
                                @"5" : @"correct1",
                                @"6" : @"excellent1",
                                @"7" : @"fantastic1",
                                @"8" : @"good1",
                                @"9" : @"goodjob1",
                                @"10" : @"greate1",
                                @"11" : @"magnificent1",
                                @"12" : @"perfect1",
                                @"13" : @"right",
                                @"14" : @"right1",
                                @"15" : @"rightold",
                                @"16" : @"nice1",
                                @"17" : @"superb1",
                                @"18" : @"youareright1",
                                };
    dictionary_sound_wrong = @{
                               @"0" : @"fault2",
                               @"1" : @"notcorrect1",
                               @"2" : @"oho1",
                               @"3" : @"wrong",
                               @"4" : @"wrong1",
                               @"5" : @"wrongold",
                               @"6" : @"youarewrong1",
                               };
    dictionary_sound_uplevel = @{
                               @"0" : @"levelup1",
                               @"1" : @"newlevel1",
                               @"2" : @"youhavepassedalllevels1",
                               };

    
    score = 0;
    level = 1;
    timeCountdownlevel = 10;
    [btn_sound setSelected:FALSE];
    [self reduceScoreLeft];
    [self new_question];
    [self performSelector:@selector(updateTextLableWithString:) withObject:str afterDelay:0.0];
    [self choose];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) startCountDown {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(reduceTimeLeft:)
                                                    userInfo:nil
                                                     repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)reduceTimeLeft:(NSTimer *)_timer {
    int type = TIME;
    if(!mathOperator.unLimitTime)
    {
        if(timeCountdown <= 0){
            [timer invalidate];
            NSString *value =[NSString stringWithFormat:@"%i", 0];
            [self calculate:value withType:type];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Player" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Save", nil];
            [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
            [alert show];
        } else {
            NSString *value =[NSString stringWithFormat:@"%i", timeCountdown];
            [self calculate:value withType:type];
            timeCountdown--;
        }
        timeCountdownlevel--;
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString*buttonPressName = [alertView buttonTitleAtIndex:buttonIndex];
    if([buttonPressName  isEqual: @"Save"])
    {
        NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
        NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"score"];
        if (dataRepresentingSavedArray != nil)
        {
            NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
            if (oldSavedArray != nil)
                arrScore = [[NSMutableArray alloc] initWithArray:oldSavedArray];
            else
                arrScore = [[NSMutableArray alloc] init];
        }
        Scores *playerScore = [[Scores alloc]init];
        playerScore.namePlayer = [alertView textFieldAtIndex:0].text;
        playerScore.score = score;
        
        [arrScore addObject:playerScore];
        
        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:arrScore] forKey:@"score"];
        [self performSegueWithIdentifier:@"to_score" sender:self];
    }
    if([buttonPressName  isEqual: @"Yes"])
    {
        [timer invalidate];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return NO;
}

- (void)reduceScoreLeft{
    int type = SCORE;
    if(score <= 0){
        score = 0;
        NSString *value =[NSString stringWithFormat:@"%i", 0];
        [self calculate:value withType:type];
    }
    else
    {
        NSString *value =[NSString stringWithFormat:@"%i", score];
        [self calculate:value withType:type];
    }
}

- (void)calculate:(NSString *)value withType:(int)type {
    //NSString *value = @"991";
    
    UIImage *scoreImage = [[UIImage alloc]init];
    // NSMutableArray *images = [[NSMutableArray alloc]initWithCapacity:score.length];
    
    if (type == SCORE) {
        if (value.length < 1 ) {
            for (int i = 0; i < 1 - value.length; i++) {
                UIImage *image = [UIImage imageNamed:@"scm0.png"];
                
                scoreImage = [self mergeImage:scoreImage withImage:image];
            }
        }
        for (int i = 0; i < value.length; i++) {
            // imageName will be @"1", then @"3" and @"2"
            NSString *imageName = [NSString stringWithFormat:@"scm%@",[[value substringToIndex:i+1] substringFromIndex:[[value substringToIndex:i+1] length] - 1]];
            NSLog(@"Name: %@", imageName);
            // add extension
            imageName = [imageName stringByAppendingString:@".png"];
            
            UIImage *image = [UIImage imageNamed:imageName];
            
            scoreImage = [self mergeImage:scoreImage withImage:image];
            
        }
        [imgScore setImage:scoreImage];
    } else if (type == TIME) {
        if(!mathOperator.unLimitTime)
        {
            if (value.length < 2 ) {
                for (int i = 0; i < 2 - value.length; i++) {
                    UIImage *image = [UIImage imageNamed:@"scm0.png"];
                    
                    scoreImage = [self mergeImage:scoreImage withImage:image];
                }
            }
            for (int i = 0; i < value.length; i++) {
                // imageName will be @"1", then @"3" and @"2"
                NSString *imageName = [NSString stringWithFormat:@"scm%@",[[value substringToIndex:i+1] substringFromIndex:[[value substringToIndex:i+1] length] - 1]];
                NSLog(@"Name: %@", imageName);
                // add extension
                imageName = [imageName stringByAppendingString:@".png"];
                
                UIImage *image = [UIImage imageNamed:imageName];
                
                scoreImage = [self mergeImage:scoreImage withImage:image];
                
            }
        }
        else
        {
            for (int i = 0; i < value.length; i++) {
                // imageName will be @"1", then @"3" and @"2"
                NSString *imageName = [NSString stringWithFormat:@"%@",[[value substringToIndex:i+1] substringFromIndex:[[value substringToIndex:i+1] length] - 1]];
                NSLog(@"Name: %@", imageName);
                // add extension
                imageName = [imageName stringByAppendingString:@".png"];
                
                UIImage *image = [UIImage imageNamed:imageName];
                
                scoreImage = [self mergeImage:scoreImage withImage:image];
                
            }
        }
        [imgTimer setImage:scoreImage];
    }
}

- (UIImage*)mergeImage:(UIImage*)first withImage:(UIImage*)second
{
    // get size of the first image
    CGImageRef firstImageRef = first.CGImage;
    CGFloat firstWidth = CGImageGetWidth(firstImageRef);
    CGFloat firstHeight = CGImageGetHeight(firstImageRef);
    
    // get size of the second image
    CGImageRef secondImageRef = second.CGImage;
    CGFloat secondWidth = CGImageGetWidth(secondImageRef);
    CGFloat secondHeight = CGImageGetHeight(secondImageRef);
    
    // build merged size
    CGSize mergedSize = CGSizeMake(firstWidth + secondWidth, MAX(firstHeight, secondHeight));
    
    // capture image context ref
    UIGraphicsBeginImageContext(mergedSize);
    
    //Draw images onto the context
    [first drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
    [second drawInRect:CGRectMake(firstWidth, 0, secondWidth, secondHeight)];
    
    // assign context to new UIImage
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // end context
    UIGraphicsEndImageContext();
    
    return newImage;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)question_mod_1
{
    mode = 1;
    dau = arc4random()%2;
    if(level<=2)
    {
        so_1 = arc4random() % 10;
        so_2 = arc4random() % 10;
    }
    if(level>2 && level<=4)
    {
        so_1 = arc4random() % 20;
        so_2 = arc4random() % 20;
    }
    if(level>4 && level<=6)
    {
        so_1 = arc4random() % 30;
        so_2 = arc4random() % 30;
    }
    if(level>6)
    {
        so_1 = arc4random() % 50;
        so_2 = arc4random() % 50;
    }
    str = [NSString stringWithFormat:@"%i",so_1];
    if(dau==0)
    {
        str = [str stringByAppendingString:@" - "];
        kq = so_1 - so_2;
    }
    else
    {
        str = [str stringByAppendingString:@" + "];
        kq = so_1 + so_2;
    }
    str = [str stringByAppendingString:[NSString stringWithFormat:@"%i = ?",so_2]];
    count = 0;
    
}

- (void)question_mod_2
{
    mode = 2;
    dau = arc4random()%2;
    if(level<=4)
    {
        so_1 = arc4random() % 10;
        so_2 = arc4random() % 10;
    }
    if(level>4)
    {
        so_1 = arc4random() % 20;
        so_2 = arc4random() % 20;
    }
    str = [NSString stringWithFormat:@"%i",so_1];
    if(dau==0)
    {
        str = [str stringByAppendingString:@" * "];
        kq = so_1 * so_2;
    }
    else
    {
        if(level<=4)
        {
            while((so_2==0)||(so_1%so_2!=0))
            {
                so_2 = arc4random() % 10;
                
            }
        }
        if(level>4)
        {
            while((so_2==0)||(so_1%so_2!=0))
            {
                so_2 = arc4random() % 20;
                
            }
        }
        str = [str stringByAppendingString:@" : "];
        kq = so_1 / so_2;
    }
    str = [str stringByAppendingString:[NSString stringWithFormat:@"%i = ?",so_2]];
    count = 0;
    
}

- (void)question_mod_3
{
    mode = 3;
    dau = arc4random()%2;
    if(level<=4)
    {
        num_1 = arc4random() % 50;
        num_2 = arc4random() % 50;
        num_3 = arc4random() % 50;
        num_4 = arc4random() % 50;
    }
    if(level>4)
    {
        num_1 = arc4random() % 100;
        num_2 = arc4random() % 100;
        num_3 = arc4random() % 100;
        num_4 = arc4random() % 100;
    }
    if(dau==0)
    {
        kq = num_1;
        if(kq<num_2)
        {
            kq = num_2;
        }
        if(kq<num_3)
        {
            kq = num_3;
        }
        if(kq<num_4)
        {
            kq = num_4;
        }
        str = @"Largest?";
    }
    else
    {
        kq = num_1;
        if(kq>num_2)
        {
            kq = num_2;
        }
        if(kq>num_3)
        {
            kq = num_3;
        }
        if(kq>num_4)
        {
            kq = num_4;
        }
        str = @"Smallest?";
    }
    count = 0;
    
}

- (void)question_mod_4
{
    mode = 4;
    dau_1 = arc4random()%4;
    dau_2 = arc4random()%4;
    so_1 = arc4random() % 10;
    so_2 = arc4random() % 10;
    so_3 = arc4random() % 10;
    str = [NSString stringWithFormat:@"(%i",so_1];
    switch (dau_1) {
        case 0:
            str = [str stringByAppendingString:@" - "];
            kq = so_1 - so_2;
            break;
        case 1:
            str = [str stringByAppendingString:@" + "];
            kq = so_1 + so_2;
            break;
        case 2:
            str = [str stringByAppendingString:@" * "];
            kq = so_1 * so_2;
            break;
        case 3:
            str = [str stringByAppendingString:@" : "];
            while((so_2==0)||(so_1%so_2!=0))
            {
                so_2 = arc4random() % 10;
                
            }
            kq = so_1 / so_2;
            break;
        default:
            break;
    }
    str = [str stringByAppendingString:[NSString stringWithFormat:@"%i)",so_2]];
    switch (dau_2) {
        case 0:
            str = [str stringByAppendingString:@" - "];
            kq = kq - so_3;
            break;
        case 1:
            str = [str stringByAppendingString:@" + "];
            kq = kq + so_3;
            break;
        case 2:
            str = [str stringByAppendingString:@" * "];
            kq = kq * so_3;
            break;
        case 3:
            str = [str stringByAppendingString:@" : "];
            while((so_3==0)||(kq%so_3!=0))
            {
                so_3 = arc4random() % 10;
                
            }
            kq = kq / so_3;
            break;
        default:
            break;
    }
    str = [str stringByAppendingString:[NSString stringWithFormat:@"%i = ?",so_3]];
    count = 0;
    
}

- (void)question_mod_5
{
    mode = 5;
    
    if(level<=4)
    {
        kq_tu = arc4random() % 5;
        do
        {
            kq_mau = arc4random() % 10;
            
        } while(kq_mau==0);
    }
    if(level>4)
    {
        kq_tu = arc4random() % 10;
        do
        {
            kq_mau = arc4random() % 20;
            
        } while(kq_mau==0);
    }
    str = [NSString stringWithFormat:@"%i/%i",kq_tu,kq_mau];
    NSLog(@"%@",str);
    count = 0;
    
}

- (void)choose
{
    int ranchoose = arc4random()%4;
    if(mode==1)
    {
        switch (ranchoose) {
            case 0:
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 1:
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 2:
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 3:
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            default:
                break;
        }

    }
    if(mode==2)
    {
        switch (ranchoose) {
            case 0:
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 1:
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 2:
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 3:
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            default:
                break;
        }
        
    }
    if(mode==3)
    {
        switch (ranchoose) {
            case 0:
                if(kq==num_1)
                {
                    [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                    [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                    [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                    [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];

                }
                    if(kq==num_2)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];

                    }
                    if(kq==num_3)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_4)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        
                    }
                break;
            case 1:
                if(kq==num_1)
                {
                    [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                    [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                    [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                    [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                    
                }
                    if(kq==num_2)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_3)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_4)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        
                    }
                break;
            case 2:
                if(kq==num_1)
                {
                    [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                    [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                    [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                    [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                    
                }
                    if(kq==num_2)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_3)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_4)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        
                    }
                break;
            case 3:
                if(kq==num_1)
                {
                    [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                    [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                    [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                    [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                    
                }
                    if(kq==num_2)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_3)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_4] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        
                    }
                    if(kq==num_4)
                    {
                        [anw_1 setTitle:[NSString stringWithFormat:@"%i",num_1] forState:UIControlStateNormal];
                        [anw_2 setTitle:[NSString stringWithFormat:@"%i",num_2] forState:UIControlStateNormal];
                        [anw_3 setTitle:[NSString stringWithFormat:@"%i",num_3] forState:UIControlStateNormal];
                        [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                        
                    }
                break;
            default:
                break;
        }
        
    }
    if(mode==4)
    {
        switch (ranchoose) {
            case 0:
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 1:
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 2:
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            case 3:
                [anw_4 setTitle:[NSString stringWithFormat:@"%i",kq] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i",arc4random() % 100] forState:UIControlStateNormal];
                break;
            default:
                break;
        }
        
    }
    if(mode==5)
    {
        switch (ranchoose) {
            case 0:
                [anw_1 setTitle:[NSString stringWithFormat:@"%i/%i",kq_tu*2,kq_mau*2] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                break;
            case 1:
                [anw_2 setTitle:[NSString stringWithFormat:@"%i/%i",kq_tu*2,kq_mau*2] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                break;
            case 2:
                [anw_3 setTitle:[NSString stringWithFormat:@"%i/%i",kq_tu*2,kq_mau*2] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_4 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                break;
            case 3:
                [anw_4 setTitle:[NSString stringWithFormat:@"%i/%i",kq_tu*2,kq_mau*2] forState:UIControlStateNormal];
                [anw_1 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_2 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                [anw_3 setTitle:[NSString stringWithFormat:@"%i/%i",(arc4random() % 10)*2,(arc4random() % 20)*2] forState:UIControlStateNormal];
                break;
            default:
                break;
        }
        
    }
    
}

- (IBAction)anwser:(id)sender {
    bool flag = FALSE;
    if([anw_1 isTouchInside])
    {
        if(mode==5)
        {
            NSString*str_anw = [anw_1 titleForState:UIControlStateNormal];
            NSArray*componet = [str_anw componentsSeparatedByString:@"/"];
            int tu = [[componet objectAtIndex:0] intValue];
            int mau = [[componet objectAtIndex:1] intValue];
            if(kq_tu*2==tu&&kq_mau*2==mau)
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        else
        {
            if(kq==[[anw_1 titleForState:UIControlStateNormal] intValue])
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        
        [anw_1 setSelected:TRUE];
        
    }
    if([anw_2 isTouchInside])
    {
        if(mode==5)
        {
            NSString*str_anw = [anw_2 titleForState:UIControlStateNormal];
            NSArray*componet = [str_anw componentsSeparatedByString:@"/"];
            int tu = [[componet objectAtIndex:0] intValue];
            int mau = [[componet objectAtIndex:1] intValue];
            if(kq_tu*2==tu&&kq_mau*2==mau)
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        else
        {
            if(kq==[[anw_2 titleForState:UIControlStateNormal] intValue])
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        [anw_2 setSelected:TRUE];
    }
    if([anw_3 isTouchInside])
    {
        if(mode==5)
        {
            NSString*str_anw = [anw_3 titleForState:UIControlStateNormal];
            NSArray*componet = [str_anw componentsSeparatedByString:@"/"];
            int tu = [[componet objectAtIndex:0] intValue];
            int mau = [[componet objectAtIndex:1] intValue];
            if(kq_tu*2==tu&&kq_mau*2==mau)
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        else
        {
            if(kq==[[anw_3 titleForState:UIControlStateNormal] intValue])
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        [anw_3 setSelected:TRUE];
    }
    if([anw_4 isTouchInside])
    {
        if(mode==5)
        {
            NSString*str_anw = [anw_4 titleForState:UIControlStateNormal];
            NSArray*componet = [str_anw componentsSeparatedByString:@"/"];
            int tu = [[componet objectAtIndex:0] intValue];
            int mau = [[componet objectAtIndex:1] intValue];
            if(kq_tu*2==tu&&kq_mau*2==mau)
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        else
        {
            if(kq==[[anw_4 titleForState:UIControlStateNormal] intValue])
            {
                flag = TRUE;
            }
            else
            {
                flag = FALSE;
            }
        }
        [anw_4 setSelected:TRUE];
        
    }
    if (flag==TRUE) {
        if(btn_sound.selected == FALSE)
        {
            NSArray *keys = dictionary_sound_right.allKeys;
            NSString*strsound = [dictionary_sound_right objectForKey:keys[arc4random_uniform((int)keys.count)]];
            filePath = [[NSBundle mainBundle] pathForResource:strsound
                                                       ofType:@"mp3"];
            fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
            audioPlayer = [[AVAudioPlayer alloc]
                           initWithContentsOfURL:fileURL error:nil];
            [audioPlayer prepareToPlay];
            audioPlayer.currentTime = 0;
            [audioPlayer play];
        }
        if(!mathOperator.unLimitTime)
        {
            timeCountdown = timeCountdown + 5;
            if(timeCountdownlevel>3)
            {
                score = score + timeCountdownlevel;
            }
            else
            {
                score = score + 3;
            }
        }
        else
        {
            score = score + 3;
        }
        [self reduceScoreLeft];
        [self performSelector:@selector(updateTextLableWithString:) withObject:@"Right!!!" afterDelay:0.0];
        [self new_question];
        if((score>=50) && (level==1))
        {
                level = 2;
                timeCountdown = 50;
                [self loadLevel:level];
            
        }
        if((score>=100) && (level==2))
        {
                level = 3;
                timeCountdown = 55;
                [self loadLevel:level];
        }
        if((score>=175) && (level==3))
        {
            level = 4;
            timeCountdown = 60;
            [self loadLevel:level];
        }
        if((score>=275) && (level==4))
        {
            level = 5;
            timeCountdown = 65;
            [self loadLevel:level];
        }
        if((score>=400) && (level==5))
        {
            level = 6;
            timeCountdown = 70;
            [self loadLevel:level];
        }
        if((score>=550) && (level==6))
        {
            level = 7;
            timeCountdown = 75;
            [self loadLevel:level];
        }
        if((score>=725) && (level==7))
        {
            level = 8;
            timeCountdown = 80;
            [self loadLevel:level];
        }
        if((score>=800) && (level==8))
        {
            if(btn_sound.selected == FALSE)
            {
                filePath = [[NSBundle mainBundle] pathForResource:@"winning"
                                                           ofType:@"mp3"];
                fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
                audioPlayer = [[AVAudioPlayer alloc]
                               initWithContentsOfURL:fileURL error:nil];
                [audioPlayer prepareToPlay];
                
                audioPlayer.currentTime = 0;
                
                [audioPlayer play];
            }
            
            timeCountdown = 0;
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Player" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Save", nil];
            [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
            [alert show];
            
        }
    }
    else
    {
        if(btn_sound.selected == FALSE)
        {
            NSArray *keys = dictionary_sound_wrong.allKeys;
            NSString*strsound = [dictionary_sound_wrong objectForKey:keys[arc4random_uniform((int)keys.count)]];
            filePath = [[NSBundle mainBundle] pathForResource:strsound
                                                       ofType:@"mp3"];
            fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
            audioPlayer = [[AVAudioPlayer alloc]
                           initWithContentsOfURL:fileURL error:nil];
            [audioPlayer prepareToPlay];
            
            audioPlayer.currentTime = 0;
            
            [audioPlayer play];
        }
        if(!mathOperator.unLimitTime)
        {
            timeCountdown = timeCountdown - 3;
        }
        count = count + 1;
        [self reduceScoreLeft];
        [self performSelector:@selector(updateTextLableWithString:) withObject:@"Wrong!!!" afterDelay:0.0];
        [self performSelector:@selector(updateTextLableWithString:) withObject:str afterDelay:1.0];
        if (count>=3) {
            [self new_question];
        }
    }
}

- (IBAction)btn_sound_select:(id)sender {
    if(btn_sound.selected==FALSE)
    {
        [btn_sound setSelected:TRUE];
    }
    else
    {
        [btn_sound setSelected:FALSE];
    }
}

- (void)new_question
{
    int random_mode = 0;
    timeCountdownlevel = 10;
    if(dictionary_mode.count>0)
    {
        NSArray *keys = dictionary_mode.allKeys;
        random_mode = [[dictionary_mode objectForKey:keys[arc4random_uniform((int)keys.count)]] intValue];
        NSLog(@"%i", [[dictionary_mode objectForKey:keys[arc4random_uniform((int)keys.count)]] intValue]);
    }
    switch (random_mode) {
        case 1:
            [self question_mod_1];
            break;
        case 2:
            [self question_mod_2];
            break;
        case 3:
            [self question_mod_3];
            break;
        case 4:
            [self question_mod_4];
            break;
        case 5:
            [self question_mod_5];
            break;
        default:
            [self question_mod_1];
            break;
    }
    [self performSelector:@selector(updateTextLableWithString:) withObject:str afterDelay:1.0];
    [self choose];
    [anw_1 setSelected:FALSE];
    [anw_2 setSelected:FALSE];
    [anw_3 setSelected:FALSE];
    [anw_4 setSelected:FALSE];
}

- (void) updateTextLableWithString:(NSString*)theString
{
    [lbResult setText:theString];
}

- (void) loadLevel:(int)level_up
{
    if(btn_sound.selected == FALSE)
    {
        NSArray *keys = dictionary_sound_uplevel.allKeys;
        NSString*strsound = [dictionary_sound_uplevel objectForKey:keys[arc4random_uniform((int)keys.count)]];
        filePath = [[NSBundle mainBundle] pathForResource:strsound
                                                   ofType:@"mp3"];
        fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
        audioPlayer = [[AVAudioPlayer alloc]
                       initWithContentsOfURL:fileURL error:nil];
        [audioPlayer prepareToPlay];
        audioPlayer.currentTime = 0;
        [audioPlayer play];
    }

    switch (level_up) {
        case 1:
            imgLevel.image = [UIImage imageNamed:@"level1.png"];
            break;
        case 2:
            imgLevel.image = [UIImage imageNamed:@"level2.png"];
            break;
        case 3:
            imgLevel.image = [UIImage imageNamed:@"level3.png"];
            break;
        case 4:
            imgLevel.image = [UIImage imageNamed:@"level4.png"];
            break;
        case 5:
            imgLevel.image = [UIImage imageNamed:@"level5.png"];
            break;
        case 6:
            imgLevel.image = [UIImage imageNamed:@"level6.png"];
            break;
        case 7:
            imgLevel.image = [UIImage imageNamed:@"level7.png"];
            break;
        case 8:
            imgLevel.image = [UIImage imageNamed:@"level8.png"];
            break;
        default:
            imgLevel.image = [UIImage imageNamed:@"level1.png"];
            break;
    }
}
- (IBAction)backClick:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Do you want cancel exam?" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"Yes", nil];
    [alert show];
    //[self dismissViewControllerAnimated:YES completion:nil];
}
@end
